package com.haoziqi.chapter_06;

import org.apache.commons.math3.fitting.leastsquares.EvaluationRmsChecker;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.hadoop.util.hash.Hash;

import java.util.HashSet;

/**
 * description
 * created by A on 2021/3/5
 */
public class Flink03_UV {
    public static void main(String[] args) {
        //1.创建环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);
        SingleOutputStreamOperator<UserBehavior> userBehaviorDS = env.readTextFile("input/UserBehavior.csv")
                .map(new MapFunction<String, UserBehavior>() {
                    @Override
                    public UserBehavior map(String value) throws Exception {
                        String[] datas = value.split(",");
                        return new UserBehavior(
                                Long.valueOf(datas[0]),
                                Long.valueOf(datas[1]),
                                Integer.valueOf(datas[2]),
                                datas[3],
                                Long.valueOf(datas[4])
                        );
                    }
                });
        //过滤出pv数据
        SingleOutputStreamOperator<UserBehavior> pvDS = userBehaviorDS.filter(datas -> "pv".equals(datas.getBehavior()));
        //UV数据。根据用户ID进行去重
        /*
            第一步，使用map方法拿到用户ID
            第二步, 使用process方法操作用户ID，进行去重操作
                   利用HashSet集合去重
         */
        pvDS.map(
                new MapFunction<UserBehavior, Long>() {
                    @Override
                    public Long map(UserBehavior value) throws Exception {
                        return value.getUserId();
                    }
                }
        ).process(new ProcessFunction<Long, Long>() {
            HashSet<Long> uvSet=new HashSet<>();
            @Override
            public void processElement(Long value, Context ctx, Collector<Long> out) throws Exception {
                uvSet.add(value);
                out.collect(Long.valueOf(uvSet.size()));
            }
        }).print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }



}
